package datastorage;

import java.util.Enumeration;
import java.util.Hashtable;
import javax.microedition.rms.*;
import utils.StringUtils;

public class RMSManager
{
    private String nameRMS;
    private Hashtable items;
    
    public RMSManager(String name)
    {
        nameRMS = name;
        items = new Hashtable();

        load();
    }

    public String get(String key)
    {
        if (items.containsKey(key))
        {
            return (String)items.get(key);
        }
        else
        {
            return null;
        }
    }

    public boolean containsKey(String key)
    {
        return items.containsKey(key);
    }

    public void set(String key, String value)
    {
        items.put(key, value);
    }

    public void remove(String key)
    {
        items.remove(key);
    }

    public String[] getKeys()
    {
        String[] result = new String[items.size()];
        
        int i = 0;
        Enumeration keys = items.keys();
        while (keys.hasMoreElements())
        {
            result[i++] = (String)keys.nextElement();
        }

        return result;
    }

    public final void load()
    {
        try
        {
            RecordStore recordStore = RecordStore.openRecordStore(nameRMS, true);
            RecordEnumeration re = recordStore.enumerateRecords(null, null, false);
            try
            {
                if (re.numRecords()!=0)
                {
                    re.rebuild();
                    String key, value, tmp;
                    while (re.hasNextElement())
                    {
                        int id = re.nextRecordId();
                        try
                        {
                            tmp = StringUtils.bytesToStr(recordStore.getRecord(id));
                            key = tmp.substring(0,tmp.indexOf("="));
                            value = tmp.substring(tmp.indexOf("=") + 1);

                            if (key != null && !key.equals("") && value != null)
                            {
                                items.put(key, value);
                            }
                        }
                        catch(Exception e)
                        {
                            continue;
                        }
                    }
                }
            }
            finally
            {
                re.destroy();
                recordStore.closeRecordStore();
            }
        }catch(RecordStoreException rse){}
    }

    public final void save()
    {
        //Удаляем предыдущее хранилище
        try
        {
            RecordStore.deleteRecordStore(nameRMS);
        }catch(Exception ex){}

        //Сохраняем все данные
        try
        {
            //открываем хранилище
            RecordStore recordStore = RecordStore.openRecordStore(nameRMS, true);
            try
            {
                //Пишем каждое значение
                String key, value, record;
                byte[] res;
                Enumeration keys = items.keys();
                while (keys.hasMoreElements())
                {
                    key = (String)keys.nextElement();
                    value = (String)items.get(key);
                    record = key + "=" + value;
                    res = StringUtils.strToBytes(record);                  
                    recordStore.addRecord(res,0,res.length);
                }
            }
            finally
            {
                //Закрываем хранилище
                recordStore.closeRecordStore();
            }
        }catch(Exception rse){}
    }
}
